<template>
  <el-drawer
      size="50%"
      v-model="visible"
      direction="rtl"
      :before-close="handleClose"
      :close-on-click-modal="false"
  >
    <template #header>
      <div class="drawer-header">
        <el-icon><MapLocation /></el-icon>
        地区选择
      </div>
    </template>
    <div v-loading="tableLoading">
      <li class="list-none mb-5">
        <section class="t-title">
          <el-checkbox v-model="allSelect" @change="handleSelectAll">全选</el-checkbox>
        </section>
      </li>
      <li v-for="(item, index) in mergeAreaTree" :key="item.id" class="list-none">
        <section class="t-title">
          <el-checkbox v-model="item.checked" :value="item.id" :indeterminate="item.children.filter(i => i.checked).length !== item.children.length && item.children.filter(i => i.checked).length > 0"
                       @change="handleItemChange($event, index)">
            {{ item.areaName }} ({{item.children.filter(i => i.checked).length + '/' + item.children.length }})
          </el-checkbox>
        </section>
        <section class="flex flex-wrap p-10">
          <div v-for="(province, index1) in item.children" :key="province.id" class="w-full-50">
            <section>
              <el-checkbox v-model="province.checked" :value="province.id" :indeterminate="province.children.filter(i => i.checked).length !== province.children.length && province.children.filter(i => i.checked).length > 0"
                           @change="handleProvinceChange($event, index, index1)">
                {{ province.areaName }} ({{province.children.filter(i => i.checked).length + '/' + province.children.length }})
              </el-checkbox>
              <el-icon class="cursor ml-2">
                <ArrowDown v-if="!province.show" @click="province.show = true" />
                <ArrowUp v-else @click="province.show = false" />
              </el-icon>
            </section>
            <section v-if="province.show" class="ml-5">
              <span v-for="(city,index2) in province.children" :key="city.id" class="ml-10">
                <el-checkbox v-model="city.checked" :value="city.id" :indeterminate="city.children.filter(i => i.checked).length !== city.children.length && city.children.filter(i => i.checked).length > 0"
                             @change="handleCityChange($event, index, index1, index2)">
                  {{ city.areaName }} ({{city.children.filter(i => i.checked).length + '/' + city.children.length }})
                </el-checkbox>
                <el-popover placement="bottom" :width="400" trigger="click">
                  <template #reference>
                    <el-icon class="cursor ml-2">
                      <ArrowDown />
                    </el-icon>
                  </template>
                  <div>
                    {{ city.areaName }}
                    <el-checkbox-group v-model="city.checkList">
                      <el-checkbox v-for="area in city.children" :key="area.id" :value="area.id" @change="handleAreaChange($event, index, index1, index2)">
                        {{ area.areaName }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-popover>
              </span>
            </section>
          </div>
        </section>
      </li>
    </div>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="handleCitySelect" :loading="tableLoading" :icon="Select">
          确认
        </el-button>
        <el-button @click="handleClose" :icon="Back">返回列表</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="AreaTree">
import useCurrentInstance from "@/hooks/useCurrentInstance.js";
import {cityAreas} from "@/assets/data/areaAll.js";
//import {cityAreas} from "@/assets/data/areaThird.js";
import {ArrowDown, ArrowUp, CloseBold, MapLocation, Select} from "@element-plus/icons-vue";

const {proxy} = useCurrentInstance();
const tableLoading = ref(false);
const allSelect = ref(false);
const emits = defineEmits(["select", "close"]);
const visible = ref(false);
const props = defineProps({
  drawer: {
    type: Boolean,
    required: true
  }
})

// 地址数据
const mergeAreaTree = ref([]);
function handleSelectAll(e) {
  if (e) {
    mergeAreaTree.value.forEach((item,index) => {
      item.indeterminate = false;
      item.checked = true;
      handleItemChange(e, index);
    })
  } else {
    mergeAreaTree.value = proxy._.cloneDeep(cityAreas);
  }
}

function handleItemChange(e, index) {
  mergeAreaTree.value[index].children.forEach((province) => {
    province.indeterminate = false;
    province.checked = e;
    province.children.forEach((city) => {
      city.indeterminate = false;
      city.checked = e;
      if (e) {
        city.checkList = city.children.map(item => item.id);
      } else {
        city.checkList = [];
      }
    })
  })
}

function handleProvinceChange(e, index, index1) {
  const provinceList = mergeAreaTree.value[index].children;
  const cityList = mergeAreaTree.value[index].children[index1].children;
  cityList.forEach((city) => {
    city.checked = e;
    if (e) {
      city.checkList = city.children.map(item => item.id);
    } else {
      city.checkList = [];
    }
  });
  const pLength = provinceList.filter(i => i.checked).length;
  if (pLength === 0) {
    mergeAreaTree.value[index].indeterminate = false;
  } else if (pLength < provinceList.length) {
    mergeAreaTree.value[index].indeterminate = true;
  }
}

function handleCityChange(e, index, index1, index2) {
  const provinceList = mergeAreaTree.value[index].children;
  const cityList = mergeAreaTree.value[index].children[index1].children;
  const areaList = mergeAreaTree.value[index].children[index1].children[index2].children;
  const city= mergeAreaTree.value[index].children[index1].children[index2];
  if (e) {
    areaList.checkList = city.children.map(item => item.id);
  } else {
    areaList.checkList = [];
  }
  const cLength = cityList.filter(i => i.checked).length;
  if (cLength === 0) {
    provinceList[index1].indeterminate = false;
  } else if (cLength < cityList.length) {
    provinceList[index1].indeterminate = true;
  }
  const pLength = provinceList.filter(i => i.checked).length;
  if (pLength === 0) {
    mergeAreaTree.value[index].indeterminate = false;
  } else if (pLength < provinceList.length) {
    mergeAreaTree.value[index].indeterminate = true;
  }
}

function handleAreaChange(e, index, index1, index2) {
  const city = mergeAreaTree.value[index].children[index1].children[index2];
  if(city.checkList.length === 0) {
    city.indeterminate = false;
  } else if (city.checkList.length < city.children.length) {
    city.indeterminate = true;
  }
}

function handleCitySelect() {
  const shippingMethodCites = [];
  mergeAreaTree.value.forEach((item) => {
    item.children.forEach((province) => {
      if (province.checked) {
        shippingMethodCites.push({
          areaId: province.id,
          areaName: province.areaName,
          treePath: province.treePath
        });
      } else {
        province.children.forEach((city) => {
          if (city.checked) {
            shippingMethodCites.push({
              areaId: city.id,
              areaName: city.areaName,
              treePath: city.treePath
            });
          } else {
           const list = city.children;
           const areaList = list.filter((i) => city.checkList.includes(i.id));
           areaList.forEach(item => {
             shippingMethodCites.push({
              areaId: item.id,
              areaName: item.areaName,
              treePath: item.treePath
            });
           })
          }
        })
      }
    })
  });
  emits("select", shippingMethodCites);
  handleClose();
}

//初始化选中
function selectTreeInit(list) {
  if (list.length === 1) {
    try {
      mergeAreaTree.value.forEach((itemObj) => {
        itemObj.children.forEach((province) => {
          if (province.id === list[0]) {
            itemObj.checked = true;
            province.checked = true;
            province.children.forEach((city) => {
              city.checked = true;
              city.checkList = city.children.map((item) => item.id);
            });
            throw new Error();
          }
        });
      });
    } catch (error) {
     // console.log(error);
    }
  } else if (list.length === 2) {
    try {
      mergeAreaTree.value.forEach((itemObj) => {
        itemObj.children.forEach((province) => {
          if (province.id === list[0]) {
            itemObj.indeterminate = true;
            province.indeterminate = true;
            province.children.forEach((city) => {
              if (city.id === list[1]) {
                city.checked = true;
                city.checkList = city.children.map((item) => item.id);
                throw new Error();
              }
            });
          }
        });
      });
    } catch (error) {
    //  console.log(error);
    }
  } else if (list.length === 3) {
    try {
      mergeAreaTree.value.forEach((itemObj) => {
        itemObj.children.forEach((province) => {
          if (province.id === list[0]) {
            itemObj.indeterminate = true;
            province.indeterminate = true;
            province.children.forEach((city) => {
              if (city.id === list[1]) {
                city.indeterminate = true;
                city.checkList.push(list[2]);
                throw new Error();
              }
            });
          }
        });
      });
    } catch (error) {
     // console.log(error);
    }
  }
}

//关闭弹窗
function handleClose() {
  emits('close')
}

function initInfo(areaList) {
  mergeAreaTree.value = proxy._.cloneDeep(cityAreas);
  areaList.forEach((item) => {
    item.treePath.split(",").filter((i) => !!i).map((i) => {
      selectTreeInit([i]);
    })
  })
}

//监听props.visible 值得变化
watch(() => props.drawer, v => {
  visible.value = v
})

defineExpose({
  initInfo
})
</script>

<style scoped lang="scss">
.t-title {
  background-color: #f5f5f5;
  padding: 0 10px;
}
</style>